package com.my.bbs.service.impl;

import com.my.bbs.dao.MyPostCommentMapper;
import com.my.bbs.dao.MyPostMapper;
import com.my.bbs.dao.MyUserMapper;
import com.my.bbs.entity.*;
import com.my.bbs.service.MyPostCommentService;
import com.my.bbs.util.BeanUtil;
import com.my.bbs.util.PageQueryUtil;
import com.my.bbs.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author 86187
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MyPostCommentServiceImpl implements MyPostCommentService {

    @Autowired
    private MyPostCommentMapper myPostCommentMapper;

    @Autowired
    private MyPostMapper myPostMapper;

    @Autowired
    private MyUserMapper myUserMapper;

    @Override
    @Transactional
    public Boolean addPostComment(MyPostComment postComment) {
        MyPost myPost = myPostMapper.selectByPrimaryKey(postComment.getPostId());
        if (myPost == null) {
            return false;
        }
        MyUser myUser = myUserMapper.selectByPrimaryKey(postComment.getCommentUserId());

        if (myUser == null || myUser.getUserStatus().intValue() == 1) {
            //账号已被封禁
            return false;
        }
        myPost.setPostComments(myPost.getPostComments() + 1);

        return myPostCommentMapper.insertSelective(postComment) > 0 && myPostMapper.updateByPrimaryKeySelective(myPost) > 0;
    }

    @Override
    @Transactional
    public Boolean delPostComment(Long commentId, Long userId) {

        MyPostComment myPostComment = myPostCommentMapper.selectByPrimaryKey(commentId);
        //评论不存在，不能删除
        if (myPostComment == null) {
            return false;
        }

        MyUser myUser = myUserMapper.selectByPrimaryKey(userId);

        if (myUser == null || myUser.getUserStatus().intValue() == 1) {
            //账号已被封禁
            return false;
        }

        MyPost myPost = myPostMapper.selectByPrimaryKey(myPostComment.getPostId());

        //评论所关联的帖子不存在，不能删除
        if (myPost == null) {
            return false;
        }

        Long commentCount = myPost.getPostComments() - 1;
        if (commentCount >= 0) {
            myPost.setPostComments(commentCount);
        }

        if (userId.equals(myPostComment.getCommentUserId()) || userId.equals(myPost.getPublishUserId())) {
            //这条评论所关联的user或者这条评论所关联帖子的user都可以删除该评论
            //即评论者和发帖者都可以删帖
            return myPostCommentMapper.deleteByPrimaryKey(commentId) > 0 && myPostMapper.updateByPrimaryKeySelective(myPost) > 0;
        }

        return false;
    }

    @Override
    public PageResult getCommentsByPostId(Long postId, int commentPage) {
        Map<String, Object> params = new HashMap<>(5);
        params.put("postId", postId);
        params.put("page", commentPage);
        //每页展示6条评论
        params.put("limit", 6);
        PageQueryUtil pageUtil = new PageQueryUtil(params);
        //查询评论数据
        int total = myPostCommentMapper.getTotalComments(pageUtil);
        List<MyPostComment> commentList = myPostCommentMapper.findCommentList(pageUtil);
        List<MyCommentListEntity> bbsCommentListEntities = new ArrayList<>();
        //数据格式转换
        if (!CollectionUtils.isEmpty(commentList)) {
            bbsCommentListEntities = BeanUtil.copyList(commentList, MyCommentListEntity.class);
            //当前评论者的userId
            List<Long> userIds = bbsCommentListEntities.stream().map(MyCommentListEntity::getCommentUserId).collect(Collectors.toList());
            //被回复评论的评论者userId
            List<Long> parentUserIds = bbsCommentListEntities.stream().map(MyCommentListEntity::getParentCommentUserId).collect(Collectors.toList());
            //分别查询user数据
            List<MyUser> myUsers = myUserMapper.selectByPrimaryKeys(userIds);
            List<MyUser> parentUsers = myUserMapper.selectByPrimaryKeys(parentUserIds);
            if (!CollectionUtils.isEmpty(myUsers)) {
                //封装user数据
                Map<Long, MyUser> bbsUserMap = myUsers.stream().collect(Collectors.toMap(MyUser::getUserId, Function.identity(), (entity1, entity2) -> entity1));
                for (MyCommentListEntity myCommentListEntity : bbsCommentListEntities) {
                    if (bbsUserMap.containsKey(myCommentListEntity.getCommentUserId())) {
                        //设置头像字段和昵称字段
                        MyUser tempUser = bbsUserMap.get(myCommentListEntity.getCommentUserId());
                        myCommentListEntity.setHeadImgUrl(tempUser.getHeadImgUrl());
                        myCommentListEntity.setNickName(tempUser.getNickName());
                    }
                }
            }
            if (!CollectionUtils.isEmpty(parentUsers)) {
                //添加被回复者的信息
                Map<Long, MyUser> parentUserMap = parentUsers.stream().collect(Collectors.toMap(MyUser::getUserId, Function.identity(), (entity1, entity2) -> entity1));
                for (MyCommentListEntity myCommentListEntity : bbsCommentListEntities) {
                    if (parentUserMap.containsKey(myCommentListEntity.getParentCommentUserId())) {
                        //在评论内容前加上"@xxx "
                        MyUser tempUser = parentUserMap.get(myCommentListEntity.getParentCommentUserId());
                        myCommentListEntity.setCommentBody("@" + tempUser.getNickName() + "：" + myCommentListEntity.getCommentBody());
                    }
                }
            }


        }
        PageResult pageResult = new PageResult(bbsCommentListEntities, total, pageUtil.getLimit(), pageUtil.getPage());
        return pageResult;
    }

    @Override
    public List<RecentCommentListEntity> getRecentCommentListByUserId(Long userId) {
        List<MyPostComment> recentCommentList = myPostCommentMapper.getRecentCommentListByUserId(userId);
        List<RecentCommentListEntity> recentCommentListEntities = new ArrayList<>();
        if (!CollectionUtils.isEmpty(recentCommentList)) {
            recentCommentListEntities = BeanUtil.copyList(recentCommentList, RecentCommentListEntity.class);
            //帖子id
            List<Long> postIds = recentCommentList.stream().map(MyPostComment::getPostId).collect(Collectors.toList());
            //查询帖子数据
            List<MyPost> myPosts = myPostMapper.selectByPrimaryKeys(postIds);
            if (!CollectionUtils.isEmpty(myPosts)) {
                //封装帖子数据
                Map<Long, MyPost> bbsPostMap = myPosts.stream().collect(Collectors.toMap(MyPost::getPostId, Function.identity(), (entity1, entity2) -> entity1));
                for (RecentCommentListEntity recentCommentListEntity : recentCommentListEntities) {
                    if (bbsPostMap.containsKey(recentCommentListEntity.getPostId())) {
                        //设置帖子标题
                        MyPost myPost = bbsPostMap.get(recentCommentListEntity.getPostId());
                        recentCommentListEntity.setPostTitle(myPost.getPostTitle());
                    }
                }
            }
        }
        return recentCommentListEntities;
    }
}
